package com.example.thirdhomework

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.thirdhomework.databinding.ActivityFirstBinding
import com.example.thirdhomework.databinding.ActivityThirdBinding
import java.util.logging.Handler

class ThirdActivity : AppCompatActivity() {
    val Tag="Life cycle"
    var seconds=0
    var running=false
    var wasRunning=false
    private val binding by lazy{
        ActivityThirdBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }



        Log.d(Tag,"onCreate")
        if(savedInstanceState!=null){
            seconds=savedInstanceState.getInt("seconds")
            running=savedInstanceState.getBoolean("running")
            wasRunning=savedInstanceState.getBoolean("wasRunning")
        }
       runTimer()
        binding.buttonStart.setOnClickListener{
            running=true
        }
        binding.buttonStop.setOnClickListener{
            running=false
        }
        binding.buttonRestart.setOnClickListener{
            running=true
            seconds=0
        }
    }


    fun runTimer(){
        val handler= android.os.Handler()
        val runnable=object: Runnable{
            override fun run(){
                val hours=seconds/3600
                val minutes=(seconds%3600)/60
                val secs=seconds%60
                binding.textViewTimer.text=String.format("%02d:%02d:%02d",hours,minutes,secs)
                if(running){
                    seconds++
                }
                handler.postDelayed(this,1000)
            }
        }
        handler.post(runnable)

    }
    override fun onSaveInstanceState(outState: Bundle){
        super.onSaveInstanceState(outState)
        Log.d(Tag,"onSaveInstanceState")

        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasRunning",wasRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
        Log.d(Tag,"onPause")
        wasRunning=running
        running=false
    }

    override fun onStop() {
        super.onStop()
    }



}